import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import store from '@/store'

Vue.use(VueRouter)

const router = new VueRouter({
    routes,
    scrollBehavior() {
        return { y: 0 }
    }
})

// 需要登录才能访问的路由
const loginRequired = ['/cart', '/order', '/center']

router.beforeEach((to, from, next) => {
    const token = store.state.user.token
    
    // 判断是否需要登录权限
    if (loginRequired.some(path => to.path.startsWith(path))) {
        if (token) {
            next()
        } else {
            next('/login?redirect=' + to.path)
        }
    } else {
        next()
    }
})

export default router